package com.bw.gmall.realtime.dws.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.bean.TradeSkuOrderBean;
import com.bw.gmall.realtime.common.constant.Constant;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;

//   用于在交易领域中，按商品（SKU）维度聚合订单数据，并通过时间窗口进行实时分析 订单交易量
public class DwsTradeSkuOrderWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsTradeSkuOrderWindow().start(Constant.TOPIC_DWD_TRADE_ORDER_DETAIL,Constant.TOPIC_DWD_TRADE_ORDER_DETAIL,4,10029);

    }

    //12.9交易域SKU粒度下单各窗口汇总表
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {
        // 1、ETL数据
        SingleOutputStreamOperator<JSONObject> etlStream = dataStreamSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    // 因为有撤回流,所有要过滤
                    if (s != null) {
                        JSONObject jsonObject = JSON.parseObject(s);
                        String skuId = jsonObject.getString("sku_id");
                        Long ts = jsonObject.getLong("ts");
                        if (skuId != null && ts != null) {
                            jsonObject.put("ts", ts * 1000);
                            collector.collect(jsonObject);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


        // 2、添加水位线
        SingleOutputStreamOperator<JSONObject> watermarksStream = etlStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject jsonObject, long l) {
                return jsonObject.getLong("ts");
            }
        }));

        // 3、处理回撤流
        SingleOutputStreamOperator<TradeSkuOrderBean> process =
                watermarksStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject jsonObject) throws Exception {
                return jsonObject.getString("sku_id");
            }
        }).process(new KeyedProcessFunction<String, JSONObject, TradeSkuOrderBean>() {
            private MapState<String, BigDecimal> mapState;

            // 金额这种类型，不会用Float，也不会用Double,基本都用BigDecimal
            @Override
            public void open(Configuration parameters) throws Exception {
                MapStateDescriptor<String, BigDecimal> stateDescriptor = new MapStateDescriptor<String, BigDecimal>("order_state", String.class, BigDecimal.class);
                stateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.seconds(30L)).build());
                mapState = getRuntimeContext().getMapState(stateDescriptor);
            }

            @Override
            public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, TradeSkuOrderBean>.Context context, Collector<TradeSkuOrderBean> collector) throws Exception {
                // 从状态里面取值
                BigDecimal split_total_amount = mapState.get("splitTotalAmount");// 分摊金额
                BigDecimal split_activity_amount = mapState.get("splitActivityAmount");// 活动金额
                BigDecimal split_coupon_amount = mapState.get("splitCouponAmount");// 优惠券金额
                BigDecimal original_amount = mapState.get("originalAmount");// 原始金额

                split_total_amount = split_total_amount == null ? new BigDecimal(0) : split_total_amount;
                split_activity_amount = split_activity_amount == null ? new BigDecimal(0) : split_activity_amount;
                split_coupon_amount = split_coupon_amount == null ? new BigDecimal(0) : split_coupon_amount;
                original_amount = original_amount == null ? new BigDecimal(0) : original_amount;


                // 从数据取出这金额

                BigDecimal splitTotalAmount = jsonObject.getBigDecimal("split_total_amount");
                BigDecimal splitActivityAmount = jsonObject.getBigDecimal("split_activity_amount");
                BigDecimal splitCouponAmount = jsonObject.getBigDecimal("split_coupon_amount");

                BigDecimal sku_num = jsonObject.getBigDecimal("sku_num");
                BigDecimal orderPrice = jsonObject.getBigDecimal("order_price");

                // 计算原始金额
                BigDecimal originalAmount = orderPrice.multiply(sku_num);


                // 直接往下游发
                String skuId = jsonObject.getString("sku_id");
                String skuName = jsonObject.getString("sku_name");
                String id = jsonObject.getString("id");
                Long ts = jsonObject.getLong("ts");

                collector.collect(TradeSkuOrderBean.builder()
                        .skuId(skuId)
                        .skuName(skuName)
                        .activityReduceAmount(splitActivityAmount.subtract(split_activity_amount))
                        .couponReduceAmount(splitCouponAmount.subtract(split_coupon_amount))
                        .originalAmount(originalAmount.subtract(original_amount))
                        .orderAmount(splitTotalAmount.subtract(split_total_amount))
                        .orderDetailId(id)
                        .ts(ts)
                        .build());

            }
        });

        // 4、根据SKU keyby

        // 5、 聚合
        // 6、关联Hbase维度
        // 7、写入Doris


        /**
         * sku_id  category3_id  money
         *   10       20          100
         *   10       20          200
         *
         *   10  300 手机
         *
         */
    }
}

